<?php

namespace App;

use http\Exception\BadQueryStringException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;


/**
 * App\RiskRule
 *
 * @property int $id
 * @property int $dengji 等级
 * @property string $gzmc 规则名称
 * @property string $money 金额限制
 * @property string $age 年龄限制
 * @property string $courtdetail 信息验证规则-法院信息详情个人高级版
 * @property string $c3 3C申请意向-3C租赁
 * @property string $zxf 租信分
 * @property string $zzf 租智分
 * @property string $name 名称
 * @property int $sort 排序
 * @property string $z_name 智能名称
 * @property string $ady 自定义
 * @property string|null $ultimately 最终综合条件
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule whereAdy($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule whereAge($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule whereC3($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule whereCourtdetail($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule whereDengji($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule whereGzmc($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule whereMoney($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule whereName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule whereSort($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule whereUltimately($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule whereZName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule whereZxf($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule whereZzf($value)
 * @mixin \Eloquent
 * @property int $status 状态 0 启用 1不启用
 * @property string|null $thqzdj 团火欺诈等级
 * @property string|null $jdyxyz 借贷意向验证
 * @property string|null $fxsb 风险哨兵
 * @property string|null $tsmdyz 反欺诈规则-特殊名单验证
 * @property string|null $fybzxr 反欺诈规则-法院被执行人限高版
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule whereFxsb($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule whereFybzxr($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule whereJdyxyz($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule whereStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule whereThqzdj($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule whereTsmdyz($value)
 * @property string|null $czylzs 偿债压力指数
 * @property string|null $tsmd 特殊名单
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule whereCzylzs($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\RiskRule whereTsmd($value)
 */
class RiskRule extends Model
{
    protected $table = 'risk_rules';


    const DENGJI_MAP = ['1'=>'D','2'=>'C','3'=>'B','4'=>'A','10'=>'S',0=>'未命中'];

    const STATUS_MAP  = [
        0 => '启用',
        1 => '停用',
    ];

    //获取D级的百融数据顺序
    public static function getRuleDQ()
    {
        $d = [
            'Rule_D_ApplyLoanC' => [
                'name' => '反欺诈规则-申请意向-3C租赁',
                'k' => 'Rule_D_ApplyLoanC',
                'type' => 1,
                'strategy_id' => 'DTA_BR0007661',
            ],
            'SpecialList_c' => [
                'name' => '特殊名单验证',
                'k' => 'SpecialList_c',
                'type' => 1,
                'strategy_id' => 'DTA_BR0007447',
            ],
            'Rule_D_FraudRelation_g' => [
                'name' => '反欺诈规则-团伙欺诈排查（通用版）',
                'k' => 'SpecialList_c',
                'type' => 1,
                'strategy_id' => 'DTA_BR0007443',
            ],

        ];

        $q = [
            'DTA_BR0007866' => [
                'name' => '预置_风险哨兵指数-优质',
                'k' => 'DTA_BR0007866',
                'type' => 1,
                'strategy_id' => 'DTA_BR0007866',
            ],
            'STR0056721' => [
                'name' => '补全D1Q',
                'k' => 'STR0056721',
                'type' => 1,
                'strategy_id' => 'STR0056721',
            ],
            'MCP0056722' => [
                'name' => '验证补全D1Q',
                'k' => 'MCP0056722',
                'type' => 2,
                'strategy_id' => 'MCP0056722',
            ],
        ];

        $all = array_merge($d,$q);
        $data = [
            'd' => $d,
            'q' => $q,
            'all' => $all,
        ];
        return $data;
    }

    public static function getRuleMap()
    {
        $data = [
            'age' => [
                'k' => 'age',
                'name'=>'年龄',
                'key' => 'age',
                'rule' => 'general',
            ],
            'money' => [
                'k' => 'money',
                'name'=>'金额限制',
                'key' => 'money',
                'rule' => 'general',
            ],
            'courtdetail' => [
                'k' => 'courtdetail',
                'name'=>'法院信息详情-个人高级版',
                'key' => 'infoverify_report_detail.CourtDetailPro.entryListNew.%s.matchRatio',
                'rule' => 'displace',
            ],
            'c3' => [
                'k' => 'c3',
                'name'=>'3C申请意向-3C租赁',
                'key' => 'strategy_report_detail.ApplyLoanC.%s',
                'rule' => 'displace',
            ],
            'zxf' => [
                'k' => 'zxf',
                'name'=>'租信分',
                'key' => 'strategy_report_detail.Score.scoreywstd',
                'rule' => 'general',
            ],
            'zzf' => [
                'k' => 'zzf',
                'name'=>'租智分',
                'key' => 'strategy_report_detail2.Score.scorewis',
                'rule' => 'general',
            ],
            'thqzdj' => [
                'k' => 'thqzdj',
                'name'=>'团火欺诈等级',
                'key' => 'strategy_report_detail.FraudRelation_g.list_level',
                'rule' => 'general',
            ],
            'jdyxyz' => [
                'k' => 'jdyxyz',
                'name'=>'借贷意向验证',
                'key' => 'strategy_report_detail.ApplyLoanStr.%s',
                'rule' => 'displace',
            ],
            'fxsb' => [
                'k' => 'fxsb',
                'name'=>'风险哨兵',
                'key' => 'DTA_BR0007866.scorefxsbindex_qlty.score%sbasea',
                'rule' => 'displace',
            ],
            'tsmdyz' => [
                'k' => 'tsmdyz',
                'name'=>'反欺诈-特殊名单验证',
                'key' => 'strategy_report_detail.Rule.hit_rules.rulespeciallist_c.%s',
                'rule' => 'count',
            ],
            'fybzxr' => [
                'k' => 'fybzxr',
                'name'=>'反欺诈规则-法院被执行人限高版',
                'key' => 'strategy_report_detail.Rule.hit_rules.ruleexecutionlimited.%s',
                'rule' => 'count',
            ],
            'czylzs' => [
                'k' => 'czylzs',
                'name'=>'偿债压力指数',
                'key' => 'strategy_report_detail.DebtRepayStress.nodebtscore',
                'rule' => 'general',
            ],
            'tsmd' => [
                'k' => 'tsmd',
                'name'=>'特殊名单验证',
                'key' => 'strategy_report_detail.SpecialList_c.%s',
                'rule' => 'displace',
            ],
        ];



        return $data;
    }

    /*
     * 转化成系统可识别数据
     */
    public static function conversionData($data){
        $rule = self::getRuleMap();
        $up_data = $arr = [];
        $status = true;
        $msg = $z_name = '';

        foreach ($data as $key => $val){
            if($val){
                if(isset($rule[$key])){
                    $up_data[$key] = $val;
                    //判断与的条件个数
                    $v = explode('&',$val);
                    foreach ($v as $value){
                        $a = self::getRuleData($rule[$key],$value);
                        if($a['status'] == false){
                            $status = false;
                            $msg = $msg.$a['msg'].' ';
                        }else{
                            $z_name = $z_name.$a['z_name'].' ';
                            $arr[] = $a['arr'];
                        }
                    }
                }
            }

        }

        $result = [
            'status' => $status,
            'arr' => $arr,
            'msg' => $msg,
            'z_name' => $z_name,
            'up_data' => $up_data
        ];
        return $result;
    }

    public static function getRuleData($rule,$data)
    {
        //判断是否是或方法
        $val = explode('|',$data);
        $result = [
            'arr' => [],
            'msg' => '异常部分：',
            'status' => true,
            'z_name' => '',
        ];
//        var_dump(9999999999,$val);
        if(count($val) > 1){
            //确定是或
            foreach ($val as $k => $v){
                if(empty($v)) continue;
                $a = self::getDanArray($rule,$v);
                if(!$a){
                    $result['msg'] .= $v.' ';
                    $result['status'] = false;
                }
                $result['arr'][] = $a;

                if($a[1] == 'bao'){
                    if($k > 0){
                        $result['z_name'] .= '或'.$rule['name'].'包含'.$a[2];
                    }else{
                        $result['z_name'] .= $rule['name'].'包含'.$a[2];
                    }

                }else{
                    if($k > 0){
                        $result['z_name'] .= '或'.$rule['name'].$a[1].$a[2];
                    }else{
                        $result['z_name'] .= $rule['name'].$a[1].$a[2];
                    }
                }
            }
        }else{
            //确定是是
            $a = self::getDanArray($rule,$val[0]);
            if(!$a){
                $result['msg'] .= $val[0].' ';
                $result['status'] = false;
            }
            if($a[1] == 'bao'){
                $result['z_name'] .= $rule['name'].'包含'.$a[2];
            }else{
                $result['z_name'] .= $rule['name'].$a[1].$a[2];
            }

            $result['arr'] = $a;
        }

        return  $result;
    }

    /**
     * 获取一个函数
     * @return void
     */
    public static function getDanArray($rule,$v)
    {
        $val = explode(',',$v);
        $count = count($val);
        $d0 = $d1 = $d2 = $d3 = '';
        if(!in_array($rule['rule'],['count'])){
            if($count == 1){
                if(strpos($val[0],'-')){
                    $d1 = 'bao';
                    $d2 = str_replace('-',',',$val[0]);
                }else{
                    $d1 = '==';
                    $d2 = $val[0];
                }
            }elseif($count == 2){
                if(in_array($val[0],['>','<','>=','<=','==','-'])){
                    if($val[0] == '-'){
                        $d1 = 'bao';
                        $d2 = str_replace('-',',',$val[1]);
                    }else{
                        $d1 = $val[0];
                        $d2 = $val[1];
                    }

                }else{
                    return false;
                }
            }else{
                if(in_array($val[1],['>','<','>=','<=','==','-'])){
                    if($val[1] == '-'){
                        $d1 = 'bao';
                        $d2 = str_replace('-',',',$val[2]);
                    }else{
                        $d1 = $val[1];
                        $d2 = $val[2];
                    }
                }else{
                    return false;
                }
            }
        }

        switch ($rule['rule'])
        {
            case 'general':
                $d0 = $rule['key'];
                break;
            case 'displace':
                $d0 = sprintf($rule['key'],$val[0]);
                break;
            case 'count':
                $d0 = sprintf($rule['key'],$val[0]);
                $d1 = 'count';
                if($count == 1){
                    $d2 = 1;
                }elseif($count == 2){
                    $d2 = $val[1];
                }else{
                    $d2 = $val[2];
                }
                break;
        }

        return [$d0 , $d1 , $d2];
    }

    public static function getRuleList()
    {
        $redis_key = 'rule_list';
        $rule = Redis::get($redis_key);
        if($rule){
            $rule = json_decode($rule,true);
        }else{
            $list = self::where('status',0)->get();
            $data = [
                '1'=>'d','2'=>'c','3'=>'b','4'=>'a','10'=>'s'
            ];
            $rule = [
                'd' => [],
                'c' => [],
                's' => [],
                'a' => [],
                'b' => [],
            ];
            foreach ($list as $val){
                $rule[$data[$val->dengji]][] = [
                    'and' => json_decode($val->ultimately,true),
                    'name' => $val->name,
                    'number' => $val->gzmc,
                ];
            }

            Redis::set($redis_key,json_encode($rule));

        }
        return $rule;
    }


}
